package com.zhuhjay.system.intercept;

import com.zhuhjay.common.annotation.AuthToken;
import com.zhuhjay.common.domain.ResponseJson;
import com.zhuhjay.common.enums.HttpCode;
import com.zhuhjay.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截需要token的请求
 * @author ZhuHJay
 * @date 2022/3/21 19:12
 */
@Slf4j
@Component
public class AuthTokenInterceptor implements HandlerInterceptor {

    private final static String USER_ID_KEY = "id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /* 先判断接口方法上是否有@AuthToken注解 */
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AuthToken tokenAnnotation = handlerMethod.getMethod().getAnnotation(AuthToken.class);
        /* 如果没有该注解, 那么就是不进行限制 */
        if( tokenAnnotation == null ) {
            return true;
        }

        if( request.getParameter(USER_ID_KEY) != null ){
            return true;
        }else{
            ServletUtils.writeJson(response, ResponseJson.error(HttpCode.LOGIN_FAILURE));
            return false;
        }
    }
}
